﻿param($sourceId,$managedEntityId,$vCenterServerName)

Function ExitPrematurely ($Message) {
	$discoveryData.IsSnapshot = $false
	$api.LogScriptEvent($ScriptName,1985,2,$Message)
	$discoveryData
	exit
}

$ScriptName = 'Community.VMware.Discovery.Host.ps1'
$api = new-object -comObject 'MOM.ScriptAPI'
$discoveryData = $api.CreateDiscoveryData(0, $sourceId, $managedEntityId)

Add-PSSnapin VMware.VimAutomation.Core
$connection = Connect-VIServer -Server $vCenterServerName -Force:$true

If ($connection.IsConnected -ne $True){
	ExitPrematurely ("Unable to connect to vCenter server " + $vCenterServerName)
}

$VMhosts = Get-View -ViewType HostSystem -Property Name,Parent | Select Name,Parent,MoRef

If (!$VMhosts){
	Disconnect-VIServer -Server $connection -Confirm:$false
	ExitPrematurely ("No Hosts found in vCenter " + $vCenterServerName)
}

ForEach ($VMhost in $VMhosts){

	If ($VMhost.Parent.Type -eq 'ClusterComputeResource'){
		$IsStandalone = 'False'
	}
	Else {$IsStandalone = 'True'}

	#Host Obj
	$VMhostObj = $discoveryData.CreateClassInstance("$MPElement[Name='Community.VMware.Class.Host']$")
	$VMhostObj.AddProperty("$MPElement[Name='Community.VMware.Class.Host']/HostName$", $VMhost.Name)
	$VMhostObj.AddProperty("$MPElement[Name='Community.VMware.Class.Host']/HostId$", [string]($VMhost.MoRef))
	$VMhostObj.AddProperty("$MPElement[Name='Community.VMware.Class.Host']/IsStandalone$", $IsStandalone)
	$VMhostObj.AddProperty("$MPElement[Name='Community.VMware.Class.vCenter']/vCenterServerName$", $vCenterServerName)
	$VMhostObj.AddProperty("$MPElement[Name='System!System.Entity']/DisplayName$", $VMhost.Name)
	$discoveryData.AddInstance($VMhostObj)
	
	#vCenter Obj (already discovered)
	$vCenterObj = $discoveryData.CreateClassInstance("$MPElement[Name='Community.VMware.Class.vCenter']$")
	$vCenterObj.AddProperty("$MPElement[Name='Community.VMware.Class.vCenter']/vCenterServerName$", $vCenterServerName )

	#vCenter Hosts Host
	$rel1 = $discoveryData.CreateRelationshipInstance("$MPElement[Name='Community.VMware.Relationship.vCenterHostsHost']$")
	$rel1.Source = $vCenterObj
	$rel1.Target = $VMhostObj
	$discoveryData.AddInstance($rel1)
}
Disconnect-VIServer -Server $connection -Confirm:$false
$discoveryData